<?php

namespace App\Http\Middleware;

use Closure;
use InfyOm\Generator\Utils\ResponseUtil;
use Response;
use DB;
use Illuminate\Support\Facades\Auth;
use Route;

class AuthApi
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $route = Route::currentRouteName();
        // 获取当前链接的id
        $id = DB::table("permissions")->where("name",$route)->value("id");
        $user = Auth::user();
        $roles = $user->roles;
        $roles = obj2arr($roles);
        $roleArr = array_column($roles,'id','name');
        $field = ['id'];
        $menus = '';
        if(!array_key_exists(env('ROOT_KEY'),$roleArr)){
            $menus = DB::table("menu")
                ->leftjoin("role_has_menu", "role_has_menu.menu_id",'=','menu.id')
                ->leftjoin("menu_has_permissions", "menu_has_permissions.menu_id",'=','menu.id')
                ->where("menu_has_permissions.permission_id",$id)
                ->whereIn("role_has_menu.role_id",$roleArr)
                ->select($field)
                ->get();
            $menus = obj2arr($menus);
            if(empty($menus)){
                return (Response::json(ResponseUtil::makeError("请求被拒绝"), 403));
            }
        }
        return $next($request);
    }
}
